<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form ref="queryFormRef" :model="queryParams" :inline="true" v-show="showSearch">
      <el-form-item label="角色名称">
        <el-input v-model="queryParams.keyword" style="width: 200px" placeholder="请输入角色名称" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.isDisable" placeholder="角色状态" clearable style="width: 200px">
          <el-option v-for="item in status" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>
    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb15">
      <el-col :span="1.5">
        <el-button type="success" plain class="el-icon-plus" @click="openModel(undefined)">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain :disabled="roleIdList.length === 0"  class="el-icon-delete"
          @click="handleDelete(undefined)">批量删除</el-button>
      </el-col>
        <RightToolBar @changeShow="changeShowSearch" :showSearch="showSearch" @queryTable="getList"></RightToolBar>
    </el-row>
    <!-- 表格展示 -->
    <el-table border :data="roleList" @selection-change="handleSelectionChange" v-loading="loading">
      <!-- 表格列 -->
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <!-- 角色名 -->
      <el-table-column prop="roleName" width="280" label="角色名" align="center"></el-table-column>
      <!-- 角色描述 -->
      <el-table-column prop="roleDesc" width="300" label="角色描述" align="center"></el-table-column>
      <!-- 状态 -->
      <el-table-column prop="isDisable" label="状态" align="center">
        <template #default="scope">
          <el-switch v-model="scope.row.isDisable" active-color="#13ce66" inactive-color="#ff4949" :active-value="0"
            :inactive-value="1" @change="handleChangeStatus(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <!-- 创建时间 -->
      <el-table-column prop="createTime" width="270" label="创建时间" align="center">
        <template #default="scope">
          <div class="create-time">
            <el-icon>
              <clock />
            </el-icon>
            <span style="margin-left: 10px">{{ formattedDate(scope.row.createTime) }}</span>
          </div>
        </template>
      </el-table-column>
      <!-- 操作 -->
      <el-table-column width="270" label="操作" align="center">
        <template #default="scope">
          <el-button  type="warning"
            class="el-icon-edit"
            size="mini"
            plain
            @click="openModel(scope.row)">
            编辑
          </el-button>
          <el-button v-if="scope.row.id !== '1'" type="danger" class="el-icon-delete" size="mini"
            plain @click="handleDelete(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination v-if="count > 0" :total="count" :page="queryParams.current" :limit="queryParams.size"
      @pagination="getList" />
    <!-- 添加或修改对话框 -->
    <el-dialog :title="title"  :visible.sync="addOrUpdate" width="500px" append-to-body>
      <el-form ref="roleFormRef" :model="roleForm" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input placeholder="请输入角色名称" v-model="roleForm.roleName" />
        </el-form-item>
        <el-form-item label="状态" prop="isDisable">
          <el-radio-group v-model="roleForm.isDisable">
            <el-radio v-for="dict in status" :key="dict.value" :label="dict.value">
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll">全选/全不选</el-checkbox>
          <el-checkbox v-model="menuCheckStrictly" @change="handleCheckedTreeConnect">父子联动</el-checkbox>
          <el-tree class="tree-border" :data="treeData"  :check-strictly="!menuCheckStrictly" :auto-expand-parent="false" show-checkbox ref="treeRef" node-key="id"
            :default-expand-all="false"  empty-text="加载中，请稍候..."
            :props="defaultProps"></el-tree>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleForm.roleDesc" :autosize="{ minRows: 2, maxRows: 4 }" resize="none" type="textarea"
            placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="addOrUpdate = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { formatDate } from "@/utils/date";
import {getRoleListPage, updateRoleStatus, deleteRole, addRole, getRoleMenuTree,updateRole  } from '@/api/role'
import {getMenuTree, } from '@/api/menu'
export default {
  data() {
    return {
      menuExpand: false,
      menuNodeAll: false,
      menuCheckStrictly: false,
      count: 0,
      showSearch: true,
      loading: false,
      title: "",
      addOrUpdate: false,
      queryParams: {
        current: 1,
        size: 10,
      },
      status: [
        {
          value: 0,
          label: "正常",
        },
        {
          value: 1,
          label: "禁用",
        },
      ],
      treeData: [],
      roleForm: {},
      roleIdList: [],
      roleList: [],
      defaultProps: {
        label: 'label', // 默认的节点文本字段名
        children: 'children', // 默认的子节点数组字段名
      },
      rules:{ roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],},
    }
  },
  methods: {
    getList(){
      this.loading = true;
      getRoleListPage(this.queryParams).then((data) => {
        if (data.code == 200) {
          this.roleList = data.data.recordList;
          this.count = data.data.count;
          this.loading = false;
        }
      });
    },
    //改变树结构选中状态
    handleCheckedTreeExpand(){
      if(!this.menuExpand){
        var nodes = this.$refs.treeRef.store.nodesMap;
        for (var i in nodes) {
          nodes[i].expanded = false;
        }
      }
      if(this.menuExpand)
      {
        for (var i = 0; i < this.$refs.treeRef.store._getAllNodes().length; i++) {
          this.$refs.treeRef.store._getAllNodes()[i].expanded = true;
        }
      }
    },
    handleCheckedTreeNodeAll(){
      if (this.menuNodeAll) { //全选
          this.$refs.treeRef.setCheckedNodes(this.treeData);
      } else { //全不选
          this.$refs.treeRef.setCheckedNodes([]);
      }
    },
    //父子联动
    handleCheckedTreeConnect(e){
    if (e) {
        this.menuCheckStrictly = true
      } else {
        this.menuCheckStrictly = false
      }
    },
    handleSelectionChange(selectedItems) {
     this.roleIdList = selectedItems.map((item) => item.id);
    },
    openModel(data){
      this.addOrUpdate = true;
      getMenuTree().then((data) => {
          if (data.code == 200) {
            this.treeData = data.data;
          }
      });
      if(data == undefined)
      {
        this.title = "新增角色";
        this.roleForm = {
          id: undefined,
          roleName: "",
          roleDesc: "",
          isDisable: 0,
          menuIdList: [],
        };
        this.$refs.treeRef.setCheckedKeys([]);
      }
      else
      {
          this.roleForm = {
          id: data.id,
          roleName: data.roleName,
          roleDesc: data.roleDesc,
          isDisable: data.isDisable,
        }
         getRoleMenuTree(data.id).then((res)=>{
          if(res.code == 200){
            this.$refs.treeRef.setCheckedKeys(res.data);
          }
         })
      }
    },
    getMenuAllCheckedKeys(){
      var parentIds = this.$refs.treeRef.getHalfCheckedKeys()
      var childsIds = this.$refs.treeRef.getCheckedKeys()
      this.roleForm.menuIdList = parentIds.concat(childsIds)
    },
    submitForm(){
      this.$refs.roleFormRef.validate((valid)=>{
        if(valid){
          //获取所有选中节点
          this.getMenuAllCheckedKeys();
          if(this.roleForm.id == undefined)//新增
          {
            addRole(this.roleForm).then((data)=>{
              if(data.code == 200){
                this.$message({
                  type: "success",
                  message: data.msg,
                });
                this.addOrUpdate = false;
                this.getList();
              }
            })
          }else{
            updateRole(this.roleForm).then((data)=>{
              if(data.code == 200){
                this.$message({
                  type: "success",
                  message: data.msg,
                });
                this.addOrUpdate = false;
                this.getList();
              }
            });
          }
        }else{
          return;
        }
      })
    },
    handleDelete(id){
      console.log('deleteId',id)
      if(id == undefined)
      {}
      else
      {
        this.roleIdList.push(id);
      }
      this.$confirm('是否删除选中角色?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
      deleteRole(this.roleIdList).then((data)=>{
        if(data.code == 200){
          this.$message({
            type: "success",
            message: '删除成功',
          });
          this.getList();
        }
      })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });

    },
    handleChangeStatus(data){
      updateRoleStatus({id:data.id,isDisable:data.isDisable}).then((data) => {
        if (data.code == 200) {
          this.$message({
            type: "success",
            message: data.msg,
          });
          this.getList();
        }
    });
    },
    handleQuery(){
      this.getList();
    },
    changeShowSearch(data){
      this.showSearch = data;
    },
    formattedDate(date) {
      return formatDate(date);
    },
  },
  mounted() {
    this.getList();
  },
}
</script>

<style>

</style>